spring源码自定义异常分析

查了好久,才找到spring事务对自定义异常的分析和应用,看类RuleBasedTransactionAttribute,该类的简介如下:

TransactionAttribute implementation that works out whether a given exception should cause transaction rollback by applying a number of rollback rules, both positive and negative. If no rules are relevant to the exception, it behaves like DefaultTransactionAttribute (rolling back on runtime exceptions).

spring对指定异常的回滚在于 rollbackOn 方法,该类默认的实现是在DefaultTransactionAttribute类中,而RuleBasedTransactionAttribute重写了该方法,简化后代码如下:

    /**
     * Winning rule is the shallowest rule (that is, the closest in the
     * inheritance hierarchy to the exception). If no rule applies (-1),
     * return false.
     * @see TransactionAttribute#rollbackOn(java.lang.Throwable)
     */
    @Override
    public boolean rollbackOn(Throwable ex) {
        RollbackRuleAttribute winner = null;
        int deepest = Integer.MAX_VALUE;

      // 查找匹配异常
        if (this.rollbackRules != null) {
            for (RollbackRuleAttribute rule : this.rollbackRules) {
                int depth = rule.getDepth(ex);
                if (depth >= 0 && depth < deepest) {
                    deepest = depth;
                    winner = rule;
                }
            }
        }

        // User superclass behavior (rollback on unchecked) if no rule matches.
        if (winner == null) {
            logger.trace("No relevant rollback rule found: applying default rules");
            return super.rollbackOn(ex);
        }

        return !(winner instanceof NoRollbackRuleAttribute);
    }

另外,如果我们需要在事务控制的service层类中使用try catch 去捕获异常后,会使事务回滚机制失效,因为该类的异常并没有抛出,即不触发事务管理机制。怎样才能既用try catch去捕获异常,又让出现异常后spring回滚呢?代码解决如下:

//假设这是一个service类的片段
try{ 
     //出现异常
} catch (Exception e) {
     e.printStackTrace();
     //设置手动回滚(重点!!!!!!)
     TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
 }
//此时return语句能够执行
return  xxx;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bboyzqh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值